//
//  SYBindPhoneNumViewController.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2020/8/20.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import SnapKit

//typealias ValidationResult = (valid: Bool?, message: String?)
class SYBindPhoneNumViewController: SYBaseViewController {
    
    let minUsernameLength = 5
    let maxUsernameLength = 10
    let minPasswordLength = 5
    let maxPasswordLength = 16
    let disposBag = DisposeBag()
    
    fileprivate var usernameTF: UITextField = {
        let tf = UITextField()
        tf.font = UIFont.systemFont(ofSize: 15)
        tf.textColor = .darkGray
        tf.backgroundColor = .yellow
        return tf
    }()
    fileprivate var usernameLB: UILabel = {
        let lb = UILabel()
        lb.textColor = .red
        lb.font = UIFont.systemFont(ofSize: 15)
        lb.text = "用户名必须是5-10位的"
        return lb
    }()
    fileprivate var passwordTF: UITextField = {
        let tf = UITextField()
        tf.font = UIFont.systemFont(ofSize: 15)
        tf.textColor = .darkGray
        tf.backgroundColor = .yellow
        return tf
       }()
    fileprivate var passwordLB: UILabel = {
        let lb = UILabel()
        lb.textColor = .red
        lb.font = UIFont.systemFont(ofSize: 15)
        lb.text = "密码必须是5-16位的"
        return lb
    }()
    fileprivate var loginButton: UIButton = {
        let bt = UIButton()
        bt.setTitle("登录", for: .normal)
        bt.setTitleColor(UIColor.white, for: .normal)
        bt.backgroundColor = .green
        return bt
    }()
    fileprivate var registerButton: UIButton = {
        let bt = UIButton()
        bt.setTitle("注册", for: .normal)
        bt.setTitleColor(UIColor.white, for: .normal)
        bt.backgroundColor = .green
        return bt
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        initViews()
        
    }
    
    fileprivate func initViews() {
        
        view.addSubview(usernameTF)
        view.addSubview(usernameLB)
        view.addSubview(passwordTF)
        view.addSubview(passwordLB)
        view.addSubview(loginButton)
        view.addSubview(registerButton)
        
        usernameTF.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(200)
            make.height.equalTo(60)
            make.width.equalTo(250)
        }
        usernameLB.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(260)
            make.height.equalTo(40)
            make.width.equalTo(250)
        }
        passwordTF.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(300)
            make.height.equalTo(60)
            make.width.equalTo(250)
        }
        passwordLB.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(360)
            make.height.equalTo(40)
            make.width.equalTo(250)
        }
        loginButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(400)
            make.height.equalTo(60)
            make.width.equalTo(250)
        }
        /*
         *  .map负责对UITextField中的字符进行处理，判断字符长度，是否符合要求，将判断的值返回给usernameValid和passwordValid
         *
         *  shareReplay()是RxSwift提供的一个流操作函数，它是以重播的方式通知自己的订阅者，保证在观察者订阅这个流的时候始终都能回播最后N个，shareReplay(1)表示重播最后一个。
         *  shareReplay 会返回一个新的事件序列，它监听底层序列的事件，并且通知自己的订阅者们。 解决有多个订阅者的情况下，map会被执行多次的问题。
         */
        let usernameValid = usernameTF.rx.text
            .map { $0!.count >= self.minUsernameLength && $0!.count <= self.maxUsernameLength }
            .share(replay: 1)
        
        let passwordValid = passwordTF.rx.text
            .map { $0!.count >= self.minPasswordLength && $0!.count < self.maxPasswordLength }
            .share(replay: 1)
        
        let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { (usernameValid, passwordValid) -> Bool in
            usernameValid && passwordValid
        }
        // 或者
//        let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 }
//        .shareReplay(1)
        
        /*  绑定
         *  将usernameValid和passwordTF.rx_enabled绑定，即用usernameValid来控制passwordTF是否可以输入的状态
         *  bindTo就是RxSwfit中用来进行值绑定的函数
         */
        usernameValid
            .bind(to: passwordTF.rx.isEnabled) //username通过验证，passwordTF才可以输入
            .disposed(by: disposBag)
        
        usernameValid
            .bind(to: usernameLB.rx.isHidden)
            .disposed(by: disposBag)
        
        passwordValid
            .bind(to: passwordLB.rx.isHidden)
            .disposed(by: disposBag)
        
        everythingValid
            .bind(to: loginButton.rx.isEnabled) // 用户名密码都通过验证，才可以点击按钮
            .disposed(by: disposBag)
        
        loginButton.rx.tap //绑定button点击事件
            .subscribe(onNext: { [weak self] in
                self?.showAlert()
            })
            .disposed(by: disposBag)
    }
    
    fileprivate func showAlert() {
        
        let alertVC = UIAlertController(title: "成功", message: "登录成功", preferredStyle: UIAlertController.Style.alert)
        let sureAction = UIAlertAction(title: "确定", style: UIAlertAction.Style.default) { (action) in
            print("确定")
        }
        alertVC.addAction(sureAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    

}
